<template>
  <div class="products-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>商品管理</h3>
          <div class="header-actions">
            <el-button type="success" @click="handleBatchImport">
              <el-icon><Upload /></el-icon>
              批量导入
            </el-button>
            <el-button type="warning" @click="handleBatchExport">
              <el-icon><Download /></el-icon>
              批量导出
            </el-button>
            <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
              <el-icon><Delete /></el-icon>
              批量删除
            </el-button>
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增商品
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="商品名称">
            <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable />
          </el-form-item>
          <el-form-item label="商品编码">
            <el-input v-model="searchForm.code" placeholder="请输入商品编码" clearable />
          </el-form-item>
          <el-form-item label="分类">
            <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>
              <el-option label="电子产品" value="电子产品" />
              <el-option label="服装鞋帽" value="服装鞋帽" />
              <el-option label="家居用品" value="家居用品" />
              <el-option label="食品饮料" value="食品饮料" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="启用" value="启用" />
              <el-option label="禁用" value="禁用" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="search">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table
        :data="pageData.data"
        v-loading="loading"
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="code" label="商品编码" width="120" />
        <el-table-column prop="name" label="商品名称" width="200" />
        <el-table-column prop="image" label="商品图片" width="100">
          <template #default="{ row }">
            <el-image
              v-if="row.image"
              :src="row.image"
              :preview-src-list="[row.image]"
              style="width: 50px; height: 50px;"
              fit="cover"
            />
            <span v-else class="no-image">暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column prop="specification" label="规格" width="150" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="purchasePrice" label="采购价" width="100">
          <template #default="{ row }">
            ¥{{ row.purchasePrice }}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="销售价" width="100">
          <template #default="{ row }">
            ¥{{ row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100">
          <template #default="{ row }">
            <el-tag :type="row.stock < 10 ? 'danger' : row.stock < 50 ? 'warning' : 'success'">
              {{ row.stock }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="SKU数量" width="100">
          <template #default="{ row }">
            <el-tag type="info">{{ row.skuCount || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === '启用' ? 'success' : 'danger'">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="warning" size="small" @click="handleStock(row)">
              库存调整
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination background :current-page="searchObject.no" :page-sizes="[10, 20, 50, 100]"
                       :page-size="pageData.size" :pager-count="5"
                       layout="total, sizes, prev, pager, next, jumper" :page-count="pageData.totalPage"
                       :total="pageData.total" @size-change="sizeChange" @current-change="pageChange">
        </el-pagination>
      </div>
    </el-card>


    <!-- 库存调整对话框 -->
    <el-dialog
      v-model="stockDialogVisible"
      title="库存调整"
      width="400px"
    >
      <el-form
        ref="stockFormRef"
        :model="stockForm"
        :rules="stockRules"
        label-width="80px"
      >
        <el-form-item label="商品名称">
          <el-input v-model="currentProduct.name" disabled />
        </el-form-item>

        <el-form-item label="当前库存">
          <el-input v-model="currentProduct.stock" disabled />
        </el-form-item>

        <el-form-item label="调整类型" prop="type">
          <el-radio-group v-model="stockForm.type">
            <el-radio label="入库">入库</el-radio>
            <el-radio label="出库">出库</el-radio>
            <el-radio label="盘点">盘点</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="调整数量" prop="quantity">
          <el-input-number
            v-model="stockForm.quantity"
            :min="1"
            style="width: 100%"
            placeholder="请输入调整数量"
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="stockForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入调整备注"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="stockDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleStockSubmit" :loading="stockLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="批量导入商品"
      width="500px"
    >
      <el-upload
        class="upload-demo"
        drag
        :action="uploadAction"
        :on-success="handleImportSuccess"
        :before-upload="beforeImportUpload"
        :file-list="importFileList"
        accept=".xlsx,.xls"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            只能上传 xlsx/xls 文件，且不超过 10MB
          </div>
        </template>
      </el-upload>

      <div class="import-tips">
        <h4>导入说明：</h4>
        <ul>
          <li>请按照模板格式填写数据</li>
          <li>商品编码不能重复</li>
          <li>必填字段：商品编码、商品名称、分类、单位、采购价、销售价</li>
          <li>支持的数据格式：文本、数字、日期</li>
        </ul>
        <el-button type="primary" size="small" @click="downloadTemplate">
          下载导入模板
        </el-button>
      </div>

      <template #footer>
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmImport" :loading="importLoading">
          确定导入
        </el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {defineStore} from "pinia";
import {usePageData} from "@/uses/usePageData.js";

const router = useRouter()

// 响应式数据
const stockDialogVisible = ref(false)
const importDialogVisible = ref(false)
const stockLoading = ref(false)
const importLoading = ref(false)
const stockFormRef = ref()
const selectedRows = ref([])
const importFileList = ref([])
const uploadAction = ref('#')


const searchStore = defineStore('productStore', {

  state: () => {
    return {
      searchObject: {
        no: 1,
        size: 10,
        sortField: "id",
        sortMethod: "desc",
        shop: '',
        name: '',
        productCatalog: '',
        productGroup: ''
      }
    }
  }
})

const {searchObject} = searchStore();
const {pageData, sizeChange, pageChange, search, changeTableSort, loading} = usePageData("product_list", searchObject);

// 搜索表单
const searchForm = reactive({
  name: '',
  code: '',
  category: '',
  status: ''
})

// 库存调整表单
const stockForm = reactive({
  type: '入库',
  quantity: 1,
  remark: ''
})

const currentProduct = ref({})

// 表单验证规则
const stockRules = {
  type: [
    { required: true, message: '请选择调整类型', trigger: 'change' }
  ],
  quantity: [
    { required: true, message: '请输入调整数量', trigger: 'blur' }
  ]
}



// 表格数据


const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    code: '',
    category: '',
    status: ''
  })
  search()
}


const handleAdd = () => {
  router.push({ name: 'ProductAdd' })
}

const handleEdit = (row) => {
  router.push({ name: 'ProductAdd', query: { id: row.id } })
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    ElMessage.success('删除成功')
    search()
  } catch {
    // 用户取消删除
  }
}

const handleStock = (row) => {
  currentProduct.value = { ...row }
  stockDialogVisible.value = true
  resetStockForm()
}

const handleStockSubmit = async () => {
  if (!stockFormRef.value) return

  try {
    await stockFormRef.value.validate()
    stockLoading.value = true

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    ElMessage.success('库存调整成功')
    stockDialogVisible.value = false
    search()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    stockLoading.value = false
  }
}

const resetStockForm = () => {
  Object.assign(stockForm, {
    type: '入库',
    quantity: 1,
    remark: ''
  })
  stockFormRef.value?.clearValidate()
}


// 批量操作方法
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleBatchImport = () => {
  importDialogVisible.value = true
}

const handleBatchExport = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要导出的商品')
    return
  }

  // 模拟导出功能
  ElMessage.success(`成功导出 ${selectedRows.value.length} 个商品`)
}

const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的商品')
    return
  }

  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个商品吗？`, '批量删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    ElMessage.success(`成功删除 ${selectedRows.value.length} 个商品`)
    selectedRows.value = []
    search()
  } catch {
    // 用户取消删除
  }
}

// 批量导入相关方法
const handleImportSuccess = (response, file) => {
  importFileList.value = [file]
  ElMessage.success('文件上传成功')
}

const beforeImportUpload = (file) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                  file.type === 'application/vnd.ms-excel'
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isExcel) {
    ElMessage.error('只能上传 Excel 文件!')
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
  }
  return isExcel && isLt10M
}

const downloadTemplate = () => {
  // 模拟下载模板
  ElMessage.success('模板下载成功')
}

const confirmImport = async () => {
  if (importFileList.value.length === 0) {
    ElMessage.warning('请先上传文件')
    return
  }

  importLoading.value = true

  try {
    // 模拟导入处理
    await new Promise(resolve => setTimeout(resolve, 2000))

    ElMessage.success('批量导入成功')
    importDialogVisible.value = false
    importFileList.value = []
    search()
  } catch (error) {
    ElMessage.error('导入失败')
  } finally {
    importLoading.value = false
  }
}

// 生命周期
onMounted(() => {
  search()
})
</script>

<style scoped>
.products-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.no-image {
  color: #c0c4cc;
  font-size: 12px;
}

.import-tips {
  margin-top: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
}

.import-tips h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 14px;
}

.import-tips ul {
  margin: 10px 0;
  padding-left: 20px;
}

.import-tips li {
  margin: 5px 0;
  color: #606266;
  font-size: 13px;
}
</style>
